#include "../head/client.h"

int user_register(int socket_fd)
{
	train_t train;
	bzero(&train, sizeof(train));
	char username[1024] = {0};
	char password[1024] = {0};
	char password_verify[1024] = {0}; // 确认

	// 通知服务端用户需要注册
	memcpy(train.data, "1", strlen("1"));
	train.length = strlen("1");
	send(socket_fd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);

	while (1)
	{
		bzero(username, sizeof(username));
		printf("请输入新的用户名：\n");
		scanf("%s", username);
		getchar(); // 读回车

		while (1)
		{
			bzero(password, sizeof(password));
			bzero(password_verify, sizeof(password_verify));

			printf("请设置密码：\n");
			scanf("%s", password);
			getchar(); // 读回车

			printf("请再次确认密码：\n");
			scanf("%s", password_verify);
			getchar(); // 读回车

			if (!strcmp(password, password_verify))
				break;
			printf("两次输入密码不一致，请重新输入密码：\n");
		}
		// 将注册信息（用户名和密码）发送给服务器
		send_str(socket_fd, username); // transmit.c
		send_str(socket_fd, password); // transmit.c

		// 接收来自服务器的确认信息，判断是否注册成功
		bzero(&train, sizeof(train));
		recvn(socket_fd, &train.length, sizeof(train.length));
		recvn(socket_fd, train.data, train.length);

		puts(train.data);
		if (!strcmp(train.data, "register_success"))
		{
			printf("注册成功！\n");
			break;
		}
		printf("该用户已存在！\n");
	}

	return 0;
}

int user_login(int socket_fd)
{
	train_t train;
	bzero(&train, sizeof(train));
	char username[1024] = {0};
	char password[1024] = {0};

	// 通知服务端用户需要登录
	memcpy(train.data, "2", strlen("2"));
	train.length = strlen("2");
	send(socket_fd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);

	while (1)
	{
		bzero(&train, sizeof(train));
		bzero(username, sizeof(username));
		bzero(password, sizeof(password));

		printf("请输入用户名：\n");
		int ret = scanf("%s", username);
		if (ret == EOF)
		{
			train.length = 0;
			send(socket_fd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);
			close(socket_fd);
			exit(0);
		}
		getchar(); // 读回车

		printf("请输入密码：\n");
		ret = scanf("%s", password);
		if (ret == EOF)
		{
			train.length = 0;
			send(socket_fd, &train, sizeof(train.length) + train.length, MSG_NOSIGNAL);
			close(socket_fd);
			exit(0);
		}
		getchar(); // 读回车

		// 发送用户名和密码给服务器
		send_str(socket_fd, username);
		send_str(socket_fd, password);

		// 接收来自服务器的确认信息，判断是否登录成功
		bzero(&train, sizeof(train));
		recvn(socket_fd, &train.length, sizeof(train.length));
		recvn(socket_fd, train.data, train.length);
		if (!strcmp(train.data, "login_success"))
		{
			printf("登录成功！\n");
			break;
		}
		printf("用户名或密码错误！请重新输入用户名和密码：\n");
	}

	return 0;
}